const Koa = require('koa');
const app = new Koa();
const router = require('@koa/router')()
const bodyParser = require('koa-bodyparser');
const jwt = require('jsonwebtoken')
const global = require('./utils/mysql')
const cors = require('koa-cors')

// 登录
router.post('/login', async ctx => {
    let { name, pwd } = ctx.request.body;

    // 判断用户是否存在
    let res = await global.query(`select * from user where name = '${name}'`)

    if (res.length == 0) {
        ctx.body = {
            code: 0,
            msg: "用户不存在"
        }
        return;
    }

    // 判断密码是否正确
    let result = await global.query(`select * from user where pwd = '${pwd}'`)
    if (result.length == 0) {
        ctx.body = {
            code: 1,
            msg: "密码不正确"
        }
        return;
    }

    // 如果全部满足条件
    let data = await global.query(`select * from user where name = '${name}' and pwd = '${pwd}'`)
    console.log(data);

    if (data.length > 0) {
        let token = jwt.sign({
            id: data[0].id,
            name: data[0].name,
        }, 'byp', { expiresIn: '1h' })

        ctx.body = {
            code: 2,
            msg: "登录成功",
            token,
            uid: data[0].id,
        }
    }
})

app.use(cors())
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(4000, () => {
    console.log("http://localhost:4000 后台服务器启动成功");
});